<template>
  <div class="dict-manage">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" inline>
        <el-form-item label="字典名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入字典名称"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="字典类型">
          <el-input
            v-model="searchForm.type"
            placeholder="请输入字典类型"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            class="search-select"
          >
            <el-option label="正常" value="normal" />
            <el-option label="停用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="left">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增字典
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedDicts.length">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
      </div>
      <div class="right">
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>导出
        </el-button>
        <el-button type="primary" @click="handleRefresh">
          <el-icon><RefreshRight /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <!-- 字典列表 -->
    <el-card shadow="hover">
      <el-table
        :data="dictList"
        border
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="字典名称" show-overflow-tooltip />
        <el-table-column prop="type" label="字典类型" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'normal' ? 'success' : 'danger'">
              {{ row.status === 'normal' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-tooltip content="字典数据" placement="top">
                <el-button type="primary" link @click.stop="handleViewData(row)">
                  <el-icon><List /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="编辑" placement="top">
                <el-button type="primary" link @click.stop="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button type="danger" link @click.stop="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 字典表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增字典' : '编辑字典'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="type">
          <el-input v-model="formData.type" placeholder="请输入字典类型">
            <template #append>
              <el-tooltip content="建议使用大写字母，如：USER_STATUS">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="normal">正常</el-radio>
            <el-radio label="disabled">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 字典数据对话框 -->
    <el-dialog
      v-model="dataDialogVisible"
      :title="`字典数据 - ${currentDict?.name}`"
      width="800px"
      destroy-on-close
    >
      <div class="dict-data-toolbar">
        <el-button type="primary" @click="handleAddData">
          <el-icon><Plus /></el-icon>新增
        </el-button>
      </div>

      <el-table
        :data="dictDataList"
        border
        stripe
        v-loading="dataLoading"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="label" label="字典标签" />
        <el-table-column prop="value" label="字典值" width="120" />
        <el-table-column prop="order" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'normal' ? 'success' : 'danger'">
              {{ row.status === 'normal' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button-group>
              <el-tooltip content="编辑" placement="top">
                <el-button type="primary" link @click="handleEditData(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button type="danger" link @click="handleDeleteData(row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 字典数据表单对话框 -->
    <el-dialog
      v-model="dataFormDialogVisible"
      :title="dataDialogType === 'add' ? '新增字典数据' : '编辑字典数据'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="dataFormRef"
        :model="dataFormData"
        :rules="dataFormRules"
        label-width="80px"
      >
        <el-form-item label="字典标签" prop="label">
          <el-input v-model="dataFormData.label" placeholder="请输入字典标签" />
        </el-form-item>
        <el-form-item label="字典值" prop="value">
          <el-input v-model="dataFormData.value" placeholder="请输入字典值" />
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-input-number v-model="dataFormData.order" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dataFormData.status">
            <el-radio label="normal">正常</el-radio>
            <el-radio label="disabled">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dataFormDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDataSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  RefreshLeft,
  Plus,
  Edit,
  Delete,
  Download,
  RefreshRight,
  List,
  QuestionFilled
} from '@element-plus/icons-vue'

// 字典项接口
interface DictItem {
  id: string | number
  name: string
  type: string
  status: 'normal' | 'disabled'
  remark?: string
  createTime: string
}

// 字典数据项接口
interface DictDataItem {
  id: string | number
  label: string
  value: string | number
  order: number
  status: 'normal' | 'disabled'
}

// 搜索表单
const searchForm = ref({
  name: '',
  type: '',
  status: ''
})

// 分页配置
const page = ref({
  current: 1,
  size: 10,
  total: 0
})

// 状态定义
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref()
const dictList = ref<DictItem[]>([])
const selectedDicts = ref<DictItem[]>([])

// 表单数据
const formData = ref({
  id: '',
  name: '',
  type: '',
  status: 'normal',
  remark: ''
})

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入字典名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请输入字典类型', trigger: 'blur' },
    { pattern: /^[A-Z][A-Z_]*$/, message: '只能使用大写字母和下划线', trigger: 'blur' }
  ]
}

// 字典数据相关
const dataDialogVisible = ref(false)
const dataFormDialogVisible = ref(false)
const dataDialogType = ref<'add' | 'edit'>('add')
const dataLoading = ref(false)
const dataFormRef = ref()
const currentDict = ref<DictItem>()
const dictDataList = ref<DictDataItem[]>([])

// 字典数据表单
const dataFormData = ref({
  id: '',
  label: '',
  value: '',
  order: 0,
  status: 'normal'
})

// 字典数据表单校验规则
const dataFormRules = {
  label: [
    { required: true, message: '请输入字典标签', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入字典值', trigger: 'blur' }
  ]
}

// 搜索方法
const handleSearch = () => {
  page.value.current = 1
  fetchDictList()
}

// 重置方法
const handleReset = () => {
  searchForm.value = {
    name: '',
    type: '',
    status: ''
  }
  handleSearch()
}

// 新增方法
const handleAdd = () => {
  dialogType.value = 'add'
  formData.value = {
    id: '',
    name: '',
    type: '',
    status: 'normal',
    remark: ''
  }
  dialogVisible.value = true
}

// 编辑方法
const handleEdit = (row: DictItem) => {
  dialogType.value = 'edit'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 删除方法
const handleDelete = (row: DictItem) => {
  ElMessageBox.confirm(
    '确定要删除该字典吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里调用删除接口
    ElMessage.success('删除成功')
    fetchDictList()
  })
}

// 批量删除方法
const handleBatchDelete = () => {
  if (selectedDicts.value.length === 0) {
    ElMessage.warning('请选择要删除的字典')
    return
  }
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedDicts.value.length} 个字典吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里调用批量删除接口
    ElMessage.success('批量删除成功')
    fetchDictList()
  })
}

// 导出方法
const handleExport = () => {
  // 这里调用导出接口
  ElMessage.success('导出成功')
}

// 刷新方法
const handleRefresh = () => {
  fetchDictList()
}

// 查看字典数据
const handleViewData = (row: DictItem) => {
  currentDict.value = row
  dataDialogVisible.value = true
  fetchDictDataList()
}

// 新增字典数据
const handleAddData = () => {
  dataDialogType.value = 'add'
  dataFormData.value = {
    id: '',
    label: '',
    value: '',
    order: 0,
    status: 'normal'
  }
  dataFormDialogVisible.value = true
}

// 编辑字典数据
const handleEditData = (row: DictDataItem) => {
  dataDialogType.value = 'edit'
  dataFormData.value = { ...row }
  dataFormDialogVisible.value = true
}

// 删除字典数据
const handleDeleteData = (row: DictDataItem) => {
  ElMessageBox.confirm(
    '确定要删除该字典数据吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里调用删除接口
    ElMessage.success('删除成功')
    fetchDictDataList()
  })
}

// 提交字典数据
const handleDataSubmit = async () => {
  if (!dataFormRef.value) return
  await dataFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // 这里调用新增或编辑接口
      ElMessage.success(dataDialogType.value === 'add' ? '新增成功' : '编辑成功')
      dataFormDialogVisible.value = false
      fetchDictDataList()
    }
  })
}

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      // 这里调用新增或编辑接口
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
      dialogVisible.value = false
      fetchDictList()
    }
  })
}

// 选择变化
const handleSelectionChange = (selection: DictItem[]) => {
  selectedDicts.value = selection
}

// 行点击
const handleRowClick = (row: DictItem) => {
  handleViewData(row)
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  page.value.size = size
  fetchDictList()
}

// 页码变化
const handleCurrentChange = (current: number) => {
  page.value.current = current
  fetchDictList()
}

// 获取字典列表
const fetchDictList = () => {
  loading.value = true
  // 这里调用获取字典列表接口
  setTimeout(() => {
    // 模拟数据
    dictList.value = [
      {
        id: 1,
        name: '用户状态',
        type: 'USER_STATUS',
        status: 'normal',
        remark: '用户状态字典',
        createTime: '2024-01-01 12:00:00'
      },
      {
        id: 2,
        name: '性别',
        type: 'GENDER',
        status: 'normal',
        remark: '性别字典',
        createTime: '2024-01-01 12:00:00'
      }
    ]
    page.value.total = 100
    loading.value = false
  }, 500)
}

// 获取字典数据列表
const fetchDictDataList = () => {
  if (!currentDict.value) return
  dataLoading.value = true
  // 这里调用获取字典数据列表接口
  setTimeout(() => {
    // 模拟数据
    dictDataList.value = [
      {
        id: 1,
        label: '正常',
        value: '1',
        order: 1,
        status: 'normal'
      },
      {
        id: 2,
        label: '停用',
        value: '0',
        order: 2,
        status: 'normal'
      }
    ]
    dataLoading.value = false
  }, 500)
}

// 初始化
onMounted(() => {
  fetchDictList()
})
</script>

<style lang="scss" scoped>
.dict-manage {
  .search-card {
    margin-bottom: 16px;
    
    :deep(.el-card__body) {
      padding: 16px;
    }
    
    .search-input {
      width: 200px;
    }
    
    .search-select {
      width: 160px;
    }
  }
  
  .toolbar {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    gap: 16px;
    
    .el-button {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
      
      .el-icon {
        margin-right: 4px;
      }
    }
  }
  
  .el-card {
    border-radius: 8px;
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    }
  }
  
  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    
    .el-button-group {
      .el-button {
        padding: 4px 8px;
        
        .el-icon {
          font-size: 16px;
        }
        
        &:hover {
          .el-icon {
            transform: scale(1.2);
          }
        }
      }
    }
  }
  
  .pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
  
  :deep(.el-tag) {
    border-radius: 4px;
    
    &.el-tag--success {
      background: var(--el-color-success-light-9);
    }
    
    &.el-tag--danger {
      background: var(--el-color-danger-light-9);
    }
  }
  
  .dict-data-toolbar {
    margin-bottom: 16px;
  }
}
</style> 